package upicgame.comment.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import upicgame.comment.dao.CommentDao;
import upicgame.entity.Comments;
import upicgame.entity.Game;
import upicgame.entity.User;

import javax.annotation.Resource;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/*
 *Created by GHW
 *Description:CommentDao实现类
 *2019/12/26 20:32
 */
@Repository
public class CommentDaoImpl implements CommentDao {
    @Resource
    private SessionFactory sessionFactory;

    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    //添加评论
    @Override
    public Comments addComments(Integer uid, Integer gid, String comments) {
        //查找当前评论人
        User user = (User) getSession().createQuery("from User where id = ?").setParameter(0, uid).uniqueResult();
        //查找当前评论的游戏
        Game game = (Game) getSession().createQuery("from Game where id = ?").setParameter(0, gid).uniqueResult();
        Comments c1 = new Comments();
        //获取评论时的时间
        Date date = new Date();
        //将Date强转为String
        //使用SimpleDateFormat里的format方法进行转换，并设置格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDate = simpleDateFormat.format(date);
        c1.setUser(user);
        c1.setGame(game);
        c1.setComments(comments);
        c1.setCurrentCommentDate(currentDate);
        this.getSession().save(c1);
        return c1;
    }

    //显示所有评论
    @SuppressWarnings("unchecked")
    @Override
    public List<Comments> showAllComments(Integer gid) {
        //需要显示的信息，评论id/评论/评论时间/评论人/评论人的头像/评论人的id，在哪个游戏的评论区
        String hql = "select id,comments,currentCommentDate,user.name,user.img,user.id from Comments where game.id = ?";
        Query query = this.getSession().createQuery(hql).setParameter(0, gid);
        return (List<Comments>) query.list();
    }

    //通过id找到评论
    @Override
    public Comments findCommentsById(Integer cid) {
        return (Comments) this.getSession().createQuery("from Comments where id = ?").setParameter(0, cid).uniqueResult();

    }
    //管理员方显示所有评论
    @SuppressWarnings("unchecked")
    @Override
    public List<Comments> showAllCommentsForAdmin() {
        //评论id，评论内容，评论时间，用户id，用户名
        String hql = "select id,comments,currentCommentDate,user.id,user.name from Comments";
        Query query = this.getSession().createQuery(hql);
		System.out.println("dao"+(List<Comments>) query.list());
        return (List<Comments>) query.list();
    }

    //删除评论
    @Override
    public void delComments(Comments comments) {
        this.getSession().delete(comments);
    }

}
